<template>
  <div class="app-container">
    <div class="app-title">
      <span>单位信息编辑</span>
    </div>
    <!-- 预算单位的蓝色按钮的位置 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-col :span="1">
          <i :class="[treeShow ? 'el-icon-s-fold treeI': 'el-icon-s-unfold treeI']" @click="toggerTree" />
        </el-col>
      </el-col>
      <div class="filter-container">
        <div>
          <el-col
            style="text-align:right;margin-top: -8px;"
            :span="16"
          >
            <el-select v-model="listQuery.state" placeholder="请选择" @change="getQueryList">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
              @click="handleEdit"
            >
              编辑
            </el-button>
          </el-col>
        </div>
      </div>
    </el-row>
    <div class="grid-content bg-purple" />
    <div
      ref="box"
      class="box"
    >
      <div
        class="left"
        :class="[isActive ? 'wid':'wids']"
      >
        <div
          :class="[treeShow ? 'treeShow' : 'treeNotShow']"
          :style="{'height' : treeHeight + 'px'}"
        >
          <AgencyTree
            class="agencyTree"
            @handleTreeQuery="handleTreeQuery"
          />
        </div>
      </div>
      <div
        v-show="Show"
        class="resize"
        title="收缩侧边栏"
      />
      <div
        class="mid"
        :class="[isActive ? 'mids': 'min']"
      >
        <!-- 表格部分 -->
        <el-table
          ref="singalTable"
          v-loading="listLoading"
          :height="tableHeight"
          :data="list"
          :stripe="true"
          fit
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        
        >
          <!-- 调用 组件empty    根据数据条数生成序号-->
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" align="center" width="50" label="序号" />
          <el-table-column type="index" align="center" width="50" label="序号" />
          <!-- 将内容  row  去点 属性-->
          <el-table-column label="单位代码" align="center">
            <template slot-scope="{row}">
              <span style="float: ">{{ row.agencyCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位名称" align="center">
            <template slot-scope="{row}">
              <span style="float: ">{{ row.agencyName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="{row}">
              <!--一个 判断的写法  根据 id 判断 -->
              <span style="float: ">{{ row.id == 0 ? "未设置":"已设置" }}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- total 是条数的意思  page是当前内容数量    limit 是当前固定多少调 以及翻页   getList页面数据  -->
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
      <Drag ref="icon" />

    </div>
    <!-- 编辑页面部分 -->
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="人员编制数限制"
      :visible.sync="dialogVerifyFormVisible"
      style="padding: 0px"
      width="50%"
    >
      <el-form
        ref="dataForm"
        class="dialog-Backgroundcolor"
        :model="formData"
        label-position="right"
        label-width="0px"
      >
        <el-row>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            :loading="saveLoading"
            @click="handleSave"
          >
            保存
          </el-button>
        </el-row>
        <el-table
          ref="singalEditTable"
          v-loading="editTableListLoading"
          max-height="400"
          :data="editListData"
          :stripe="true"
          fit
          class="editTable"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column type="index" align="center" width="80" label="序号" />
          <el-table-column label="工资类型" align="center">
            <template slot-scope="scope">
              <!-- 下拉用法  通过 code  对应name -->
              <el-select v-model="scope.row.meritPayCode" placeholder="请选择" @change="bindSelectChange">
                <el-option
                  v-for="item in agencyTypeList"
                  :key="item.meritPayId"
                  :disabled="item.disabled"
                  :label="item.meritPayName"
                  :value="item.meritPayCode"
                />
              </el-select>
            </template>
          </el-table-column>
          <!-- 一个填写框   scope.row.personNum 对应实体的值 -->
          <el-table-column fixed="right" label="人员限制" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.personNum"
                onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"
                style="width:auto"
                maxlength="4"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
    <Enclosure
      ref="enc"
      :middle-table-code="1"
    />
  </div>
</template>
<script>
import { getAgencyPersonRestrictPage, insertUpdateAgencyPersonRestrict, agencyType, queryAgencyId, currentUnit } from '@/api/unitInformationMaintenance/personnellimitEdit'
import Pagination from '@/components/Pagination'
import Enclosure from '@/components/Enclosure'
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
export default {
  components: { Enclosure, Pagination, tableEmpty, AgencyTree, Drag },
  // filters: {
  //   bankFilters(type, that) {
  //     const agencyTypeList = that.agencyTypeList
  //     for (const item in agencyTypeList) {
  //       if (agencyTypeList[item].code === type) {
  //         return agencyTypeList[item].name
  //       }
  //     }
  //   }
  // },
  data() {
    return {
      isSet: null,
      options: [{
        value: 0,
        label: '全部'
      }, {
        value: 1,
        label: '已设置'
      }, {
        value: 2,
        label: '未设置'
      }],
      treeHeight: null,
      isActive: true,
      tableHeight: null,
      Show: false,
      selection: [],
      treeShow: false,
      that: this,
      list: null,
      total: 0,
      listLoading: true,
      saveLoading: false,
      listQuery: {
        page: 1,
        limit: 200,
        agencyId: '',
        state: 0
      },
      formDsiabled: false,
      formData: {
        id: '',
        agencyId: '',
        agencyCode: '',
        agencyName: '',
        mofDivCode: '',
        meritPayId: '',
        meritPayName: '',
        meritPayCode: '',
        personNum: ''
      },
      dialogVerifyFormVisible: false,
      verifyLoading: false,
      dialogStatus: '',
      mofDivLists: ' ',
      editTableListLoading: false,
      agencyTypeList: '',
      addItem: {
        postId: '',
        isNewItem: ''
      },
      modifyList: [],
      editListData: [],
      agencyId: ' '
    }
  },
  watch: {
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  // 加载后运行
  created() {
    // 获取 page 数据
    this.getList()
    // 获取 工资类型
    this.getAgencyType()
  },
  // 路由钩子 般在初始化页面完成后，再对dom节点进行相关操作
  mounted() {
    this.getTbHeight()
    this.dragController()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    bindSelectChange() {
      //  获取 当前 editListData 里的 code值
      const tempList = this.editListData.map(item => item.meritPayCode)
     
      this.agencyTypeList.forEach(item => {
        // 判断 当前code 里是否被选择 选择就不可再次选择,避免重复
        tempList.includes(item.meritPayCode) ? item.disabled = true : item.disabled = false
      })
    },
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
    // 切换树是否显示
    toggerTree() {
      this.treeShow = !this.treeShow
      this.isActive = !this.isActive
      this.Show = !this.Show
    },
    // 获取数内容
    // getTree() {
    //   getDepartmentTree(this.listQuery).then(response => {
    //     this.listTree = response.data
    //   })
    // },
    // 树方法
    handleTreeQuery(data) {
      this.treeData = data
      this.handleTree(data)
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
      this.treeHeight = this.tableHeight
    },
    
    // 一个gitList 方法
    getList() {
      // 加载的时候 转圈圈
      this.listLoading = true
      // page 查询 接口
      getAgencyPersonRestrictPage(this.listQuery).then(response => {
        // 将放回 的数据 赋值给list
        this.list = response.data.rows
        // 将返回的条数 赋值给 total
        this.total = response.data.total
        // 加载的时候 数据完毕后 转圈圈停止
        this.listLoading = false
      }).catch(() => {
        // list 是一个集合数组
        this.list = []
        // total 默认为0
        this.total = 0
        // 加载的时候 数据完毕后 转圈圈停止
        this.listLoading = false
      })
    },
    // 调用 page 将当前状态 0 1 2 传入后台 进行查询
    getQueryList() {
      // 加载的时候 转圈圈
      this.listLoading = true
      // page 查询 接口
      getAgencyPersonRestrictPage(this.listQuery).then(response => {
        // 将放回 的数据 赋值给list
        this.list = response.data.rows
        // 将返回的条数 赋值给 total
        this.total = response.data.total
        // 加载的时候 数据完毕后 转圈圈停止
        this.listLoading = false
      }).catch(() => {
        // list 是一个集合数组
        this.list = []
        // total 默认为0
        this.total = 0
        // 加载的时候 数据完毕后 转圈圈停止
        this.listLoading = false
      })
    },
    // 保存成功后 刷新
    handleFilter() {
      //
      this.listQuery.page = 1
      // 状态位置保存后 变成 全部内容
      this.listQuery.state = 0
      // 调取 getList 方法重新查找 数据
      this.getList()
      // 调取 getTree   获取数内容
      // this.getTree()
    },
    handleTree(data) {
      this.listQuery.agencyId = data.id
      this.getList()
    },
    // 编辑
    handleEdit() {
      // 获取当前 表格信息中的 序号
      const selection = this.$refs.singalTable.selection
      // 判断当前序号是否等于你
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择要修改的单位',
          type: 'warning',
          duration: 4000
        })
        return
      }
      // 打开弹窗
      this.editTableListLoading = true
      // 不知道什么意思
      this.formData = Object.assign({}, this.formData, selection[0])
      // 根据id查找当前表是否有值 有值回显
      this.getAgencyId()
      // 打开弹窗
      this.dialogVerifyFormVisible = true
    },
    // 新增 方法
    handleAdd() {
      const addItem = { ...this.addItem }
      addItem.isNewItem = Math.random()
        .toString(16)
        .substr(2, 8)
      this.editListData.unshift(addItem)
    },
    // 保存方法
    handleSave() {
      // 判断当前editListData长度 是否一致
      if (this.editListData.length === 0) {
        this.$message({
          showClose: true,
          message: '请新增后,再保存',
          type: 'warning',
          duration: 4000
        })
        return
      }
      //  item.meritPayCode 和 item.personNum 是否有值 赋值给 isTrue
      const isTrue = this.editListData.every(item => {
 
       
        return item.meritPayCode && item.personNum
      })
      // 如果 isTrue 没有值 不让保存
      if (!isTrue) {
        this.$message({
          showClose: true,
          message: '请填写完整后,再保存',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.saveLoading = true
      // 创建一个集合数组
      const postIds = []
      // 获取当前值
      const editListData = this.unique()

      let panDuan=0
      editListData.forEach(item => {
        let reg = /^[0-9]\d{0,8}$/
         if (reg.test(item.personNum) != true) {
            panDuan=1
         }
      })
      if (panDuan==1) {
        this.$message({
          showClose: true,
          message: '输入有误，请输入0~99999之间的整数',
          type: 'warning',
          duration: 4000
        })
        this.saveLoading = false
        this.dialogVerifyFormVisible = false
        return
      }
      // 将当前的存入 map 循环存入 返回给后台
      editListData.forEach(item => {
        // 创建一个map
        const current = {}
        current['id'] = item.id
        current['agencyId'] = this.formData.agencyId
        current['agencyCode'] = this.formData.agencyCode
        current['agencyName'] = this.formData.agencyName
        current['mofDivCode'] = this.formData.mofDivCode
        current['meritPayId'] = item.meritPayId
        current['meritPayCode'] = item.meritPayCode
        current['meritPayName'] = item.meritPayName
        current['personNum'] = item.personNum
        // 将map 存入集合组数中
        postIds.push(current)
      })
      // 接口 插入或者保存
      insertUpdateAgencyPersonRestrict(postIds).then((response) => {
        this.dialogEditFormVisible = false
        this.$message({
          showClose: true,
          message: '修改成功',
          type: 'success',
          duration: 4000
        })
        this.saveLoading = false
        this.dialogVerifyFormVisible = false
        // 保存后调用刷新方法
        this.handleFilter()
      }).catch(() => {
        this.saveLoading = false
      })
    },
    // 获取当前值
    unique() {
      const editListData = this.editListData
      return editListData
    },
    // 删除
    handleDelete(row) {
      const index = this.editListData.indexOf(row)
      this.editListData.splice(index, 1)
      this.bindSelectChange()
    },
    // 根据id查找当前表是否有值
    getAgencyId() {
      // 根据agencyid 查这个单位下的所有人数以及状态
      queryAgencyId(this.formData.agencyId).then((response) => {
        // 将获取的数据赋值给editListData
        this.editListData = response.data
        // 当前单位下的工资类型有什么
        this.bindSelectChange()
        this.editTableListLoading = false
      })
    },
    // 根据区划查找工资类型
    getAgencyType() {
      agencyType().then((response) => {
        // 将获取的数据赋值给agencyTypeList
        this.agencyTypeList = response.data
        // 将agencyTypeList值循环 如果 已经选择 将变成不可再次选择
        this.agencyTypeList.forEach(item => {
          item.disabled = false
        })
      })
    },
    // 根据机构id查询当前单位
    getCurrentUnit() {
      currentUnit(this.formData.id).then((response) => {
        // 将获取的数据赋值给editListData
        this.editListData = response.data
        this.editTableListLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .editFormDeviation {
    margin-left: 10%;
  }
  .viewFormDeviation {
    margin-left: 6%;
  }
    .formDeviation {
    margin-left: 5%;
  }
  ::v-deep .el-select {
    .el-input {
      height: auto !important;
    }
  }
</style>
